package com.tbgov.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 1st
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 设置applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    /**
     * 通过name获取 Bean
     *
     * @param beanName bean名称
     * @return: T
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 通过class获取 Bean
     *
     * @param requiredType
     * @return: T
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }

    private static void assertApplicationContext() {
        if (SpringContextUtil.applicationContext == null) {
            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextUtil!");
        }
    }


    /**
     * 获取配置文件配置项的值
     *
     * @param key 配置项key
     */
    public static String getEnvironmentProperty(String key) {
        return getApplicationContext().getEnvironment().getProperty(key);
    }


    /**
     * 获取spring.profiles.active
     */
    public static String getActiveProfile() {
        return getApplicationContext().getEnvironment().getActiveProfiles()[0];
    }

    /**
     * 获取环境链接（生产，开发，测试）
     *
     * @param route 路由链接
     * @return java.lang.String
     *//*
    public static String getEnvironmentLink(String route) {
        String domain = SpringContextUtil.getActiveProfile();
        String environmentLink = StringUtils.contains(domain, "dev")
                ? DomainConstant.DEV_DOMAIN
                : (StringUtils.contains(domain, "test") ? DomainConstant.TEST_REQ_H5DOMAIN : DomainConstant.ONLINE_REQ_H5DOMAIN);
        if (StringUtils.isBlank(route)) {
            return environmentLink;
        }
        return environmentLink + (route.startsWith("/") ? route : "/" + route);
    }*/
}
